package com.example.administrator.liveapp.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.Image;
import android.net.Uri;
import android.os.CountDownTimer;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.adapter.LiveDetailCommentAdapter;
import com.example.administrator.liveapp.base.BaseRVAdapter;
import com.example.administrator.liveapp.base.BaseViewHolder;
import com.example.administrator.liveapp.bean.LiveDetailsBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.LogU;
import com.example.administrator.liveapp.utils.TimeChangeUtil;
import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.google.gson.Gson;
import com.sina.weibo.sdk.utils.LogUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerManager;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

/**
 * 直播详情activity
 */

public class LiveDetailsPage extends AppCompatActivity implements View.OnClickListener {
//    private Button live_details_button; //发送评论
    private TextView like_number;//评论数
    private TextView live_editText_content;
    private LiveDetailCommentAdapter liveDetailsAdapter;//一级评论适配器
    private TextView live_comments_text; //评论数
    private RecyclerView live_details_recyclerview;
    private View loadView;//loding页面（加载页）
    private LinearLayout live_details_profile;
    private TextView tel;
    private String msURI;

    private String consumerId = "";//用户Id
    private String videoId;//直播视频id
    private String playstatics;//播放状态
    private LiveDetailsBean bean;
    private TextView live_details_title;
    private TextView live_details_name;//主讲人\职位
    private TextView live_details_time;
    private RadioButton live_number;//浏览量
    private TextView live_up_number;//点赞数
    private ImageView live_like;//用户点赞
    private TextView live_details_introduce;//简介
    private ImageView hides;//显示隐藏简介
    private TextView stores;
    private NestedScrollView scroll;
    private TextView live_money;//直播价格
    private TextView need_pay;//是否属于免费组
    private ImageView play;//播放按钮
    private ImageView video_return;//返回
    private ImageView share;//分享


    private TextView The_countdown;//倒计时显示
    private Button appointment_button;//立即预约
    private int mDisplayDays;//天
    private int mDisplayHours;//时
    private int mDisplayMinutes;//分
    private int mDisplaySeconds;//秒
    private long time;//系统当前时间
    private long countdownTime;

    private LinearLayout huifang;
    private TextView xiahua;

    //支付
    private PopupWindow mPopWindow;
    private Button payButton;
    private ImageView zhifubao;
    private ImageView weixin;
    private RelativeLayout zfb,wx;
    private IWXAPI mIwxapi;
    private TextView money;
    /**
     * 倒计时:
     */
    public CountDownTimer timer;

    //直播播放器
    private JCVideoPlayerStandard surfaceView;//JC播放器
    private ImageView video_image;//直播未开始展示的图片
    private FrameLayout surface_View;//播放界面
    private LinearLayout list_line;
    //直播列表
    private RecyclerView videoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApplicationUtils applicationUtils = new ApplicationUtils();
        applicationUtils.addActivity(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("action.refreshFriend");
        registerReceiver(mRefreshBroadcastReceiver, intentFilter);
        initView();
        data(1);
    }

    private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("action.refreshFriend")) {
                data(1);
            }
        }
    };

    private void initView() {
        setContentView(R.layout.live_details_page);
        list_line = (LinearLayout) findViewById(R.id.list_line);
        videoList = (RecyclerView) findViewById(R.id.videoList);
        videoList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        scroll = (NestedScrollView) findViewById(R.id.scroll);
        scroll.scrollTo(0, 0);
        Intent intent = getIntent();
        videoId = intent.getStringExtra("videoId");
        stores = (TextView) findViewById(R.id.stores);
        tel = (TextView) findViewById(R.id.tel);
        loadView = findViewById(R.id.loadView);
        loadView.setVisibility(View.VISIBLE);
        like_number = (TextView) findViewById(R.id.like_number);
        video_image = (ImageView) findViewById(R.id.video_image);
        surface_View = (FrameLayout) findViewById(R.id.surface_View);
        appointment_button = (Button) findViewById(R.id.appointment_button);
        The_countdown = (TextView) findViewById(R.id.The_countdown);
        huifang = (LinearLayout) findViewById(R.id.huifang);
        xiahua = (TextView) findViewById(R.id.xiahua);
        live_details_recyclerview = (RecyclerView) findViewById(R.id.live_details_recyclerview);
//        live_details_button = (Button) findViewById(R.id.live_details_button);
        live_editText_content = (TextView) findViewById(R.id.live_editText_content);
        live_comments_text = (TextView) findViewById(R.id.live_comments_text);
        live_details_title = (TextView) findViewById(R.id.live_details_title);
        live_details_name = (TextView) findViewById(R.id.live_details_name);
        live_details_time = (TextView) findViewById(R.id.live_details_time);
        live_number = (RadioButton) findViewById(R.id.live_number);
        live_up_number = (TextView) findViewById(R.id.live_up_number);
        live_details_introduce = (TextView) findViewById(R.id.live_details_introduce);
        live_details_profile = (LinearLayout) findViewById(R.id.live_details_profile);
        surfaceView = (JCVideoPlayerStandard) findViewById(R.id.video_view);
        live_money = (TextView) findViewById(R.id.live_money);
        need_pay = (TextView) findViewById(R.id.need_pay);
        hides = (ImageView) findViewById(R.id.hides);
        live_like = (ImageView) findViewById(R.id.live_like);
        play = (ImageView) findViewById(R.id.play);
        video_return = (ImageView) findViewById(R.id.video_return);
        share = (ImageView) findViewById(R.id.share);
        video_return.setOnClickListener(this);
        share.setOnClickListener(this);
        live_like.setOnClickListener(this);
        hides.setOnClickListener(this);
        appointment_button.setOnClickListener(this);
//        live_details_button.setOnClickListener(this);
        live_editText_content.setOnClickListener(this);
        tel.setOnClickListener(this);
        stores.setOnClickListener(this);
        play.setOnClickListener(this);
        if (ApplicationUtils.getInstance().loginBean != null) {
            consumerId = ApplicationUtils.getInstance().loginBean.getConsumerid();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (timer != null) {
            timer.cancel();
        }
        data(0);
    }

    /**
     * 调用拨号界面
     *
     * @param tel 电话号码
     */
    private void call(String tel) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tel));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
    }

    private int position = 1;
    int count = 0;
    int positions = 0;//区分支付宝支付和微信支付
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_return:
                finish();
                break;
            case R.id.share://直播分享
                UMWeb web = new UMWeb(AppUrl.URL + "index.php/ban/index/video.html?id="+videoId);
                String Url = bean.getVideo().getBackimgurl();
                String ImageUrl = "";
                if (Url != null && !Url.equals("")) {
                    ImageUrl = Url.substring(1, Url.indexOf("|"));
                }
                UMImage image = new UMImage(LiveDetailsPage.this, AppUrl.URL + ImageUrl);//资源文件
                UMImage thumb = new UMImage(this, AppUrl.URL + ImageUrl);
                image.setThumb(thumb);
                web.setThumb(thumb);  //缩略图
                web.setTitle(bean.getVideo().getVideotitle());//标题
                web.setDescription(bean.getVideo().getVideodescribe());//描述

                //带面板文本分享
                new ShareAction(LiveDetailsPage.this)
                        .withMedia(web)
                        .setDisplayList(SHARE_MEDIA.WEIXIN_CIRCLE,SHARE_MEDIA.WEIXIN ,SHARE_MEDIA.SINA, SHARE_MEDIA.QQ)
                        .setCallback(shareListener)
                        .open();
                break;
            case R.id.stores:
                call(bean.getStore().getStoretel());
                break;
            case R.id.live_like:
                if (consumerId != null && !consumerId.equals("")) {
                    String urls = AppUrl.URLS + AppUrl.LikeUrl;
                    Map<String, String> maps = new HashMap<>();
                    maps.put("likeTid", "1");
                    maps.put("likeUid", consumerId);
                    maps.put("likeFid", bean.getVideo().getVideoid());
                    XUtils.Get(urls, maps, new MyCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            super.onSuccess(result);

                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(result);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String code = jsonObject.optString("code");
                            if (code.equals("7910") || code.equals("7400")) {
                                count = 1;
                                live_like.setImageResource(R.drawable.praise);
                            } else if (code.equals("7700")) {
                                live_like.setImageResource(R.drawable.praise_w);
                                count = 2;
                            }
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            super.onError(ex, isOnCallback);
                            Toast.makeText(LiveDetailsPage.this, "点赞错误", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFinished() {
                            super.onFinished();
                            int likes = Integer.parseInt(live_up_number.getText().toString());
                            if (count == 1) {
                                live_up_number.setText(likes + 1 + "");
                            } else if (count == 2) {
                                live_up_number.setText(likes - 1 + "");
                            }
                        }
                    });
                } else {
                    startActivity(new Intent(this,WxLoginPage.class));
                    Toast.makeText(this, "用户未登录，请登录后点赞", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.hides:
                if (position == 0) {
                    /** 设置旋转动画 */
                    RotateAnimation rotate = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    rotate.setDuration(200);//设置动画持续时间
                    rotate.setRepeatCount(0);//设置重复次数
                    rotate.setFillAfter(true);//动画执行完后是否停留在执行完的状态
                    rotate.setStartOffset(10);//执行前的等待时间
                    hides.startAnimation(rotate);
                    live_details_profile.setVisibility(View.GONE);
                    position = 1;
                } else if (position == 1) {
                    /** 设置旋转动画 */
                    RotateAnimation rotate = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    rotate.setDuration(200);//设置动画持续时间
                    rotate.setRepeatCount(0);//设置重复次数
                    rotate.setFillAfter(true);//动画执行完后是否停留在执行完的状态
                    rotate.setStartOffset(10);//执行前的等待时间
                    hides.startAnimation(rotate);
                    live_details_profile.setVisibility(View.VISIBLE);
                    position = 0;
                }
                break;
            case R.id.zfb:
                positions = 1;
                zhifubao.setImageResource(R.drawable.check);
                weixin.setImageResource(R.drawable.no_check);
                break;
            case R.id.wx:
                positions = 0;
                weixin.setImageResource(R.drawable.check);
                zhifubao.setImageResource(R.drawable.no_check);
                break;
            case R.id.pay_button:
                if (positions == 1) {
                    Toast.makeText(this, "支付宝支付正在开发中", Toast.LENGTH_SHORT).show();
                } else if (positions == 0) {
                    if (mPopWindow != null && mPopWindow.isShowing()) {
                        mPopWindow.dismiss();
                    }
                    requestPay();
                }
                break;
            case R.id.appointment_button://预约报名
                if (ApplicationUtils.getInstance().loginBean != null) {
                    if (ApplicationUtils.getInstance().loginBean != null && ApplicationUtils.getInstance().loginBean.getConsumertel() == null) {
                        Toast.makeText(LiveDetailsPage.this, "请先绑定手机号", Toast.LENGTH_SHORT).show();
                        Intent intent1 = new Intent(LiveDetailsPage.this, BindingPhonePage.class);
                        startActivity(intent1);
                        overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        return;
                    }
                    if (bean.getVideo().getOrderStatus().equals("1")) {
                        String url = AppUrl.URLS + AppUrl.videoorderUrl;
                        Map<String, String> map = new HashMap<>();
                        map.put("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                        map.put("statics", "1");
                        map.put("videoId", videoId);
                        map.put("status", "1");
                        XUtils.Get(url, map, new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                String code = jsonObject.optString("code");
                                if (code.equals("6801")) {
                                    Toast.makeText(LiveDetailsPage.this, "预约成功", Toast.LENGTH_SHORT).show();
                                    appointment_button.setText("已预约");
                                    appointment_button.setEnabled(false);
                                    appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                                } else {
                                    Toast.makeText(LiveDetailsPage.this, "您已预约请勿重复预约", Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
                                Toast.makeText(LiveDetailsPage.this, "错误", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        showPopupWindow();
                    }
                } else {
                    startActivity(new Intent(LiveDetailsPage.this,WxLoginPage.class));
                    Toast.makeText(this, "用户未登录，请先登录!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.play:
                if (ApplicationUtils.getInstance().loginBean != null) {
                    if (ApplicationUtils.getInstance().loginBean != null && ApplicationUtils.getInstance().loginBean.getConsumertel() == null) {
                        Toast.makeText(LiveDetailsPage.this, "请先绑定手机号", Toast.LENGTH_SHORT).show();
                        Intent intent1 = new Intent(LiveDetailsPage.this, BindingPhonePage.class);
                        startActivity(intent1);
                        overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        return;
                    }
                    if (!bean.getVideo().getOrderStatus().equals("1")) {
                        showPopupWindow();
                    }
                }else{
                    startActivity(new Intent(LiveDetailsPage.this,WxLoginPage.class));
                    Toast.makeText(this, "用户未登录，请先登录!", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.live_editText_content://一级评论]
                showPopupWindow2();
                break;
        }
    }

    private PopupWindow mPopWindow2;

    private void showPopupWindow2() {
        //设置contentView
        View contentView = LayoutInflater.from(LiveDetailsPage.this).inflate(R.layout.activity_comments, null);
        mPopWindow2 = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopWindow2.setContentView(contentView);
        mPopWindow2.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        mPopWindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        final EditText comment = (EditText) contentView.findViewById(R.id.comment);
        Button article_details_button = (Button) contentView.findViewById(R.id.article_details_button);
        InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        //这里给它设置了弹出的时间，
        imm.toggleSoftInput(100, InputMethodManager.HIDE_NOT_ALWAYS);
        //设置各个控件的点击响应
        article_details_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (consumerId != null && !consumerId.equals("")) {
                    if (TextUtils.isEmpty(comment.getText())) {
                        Toast.makeText(getApplicationContext(), "评论不能为空", Toast.LENGTH_SHORT).show();
                    } else {
                        String url = AppUrl.URLS + AppUrl.CommentariesURL;
                        Map<String, String> map = new HashMap<>();
                        map.put("commentUid", consumerId);
                        map.put("commentFid", bean.getVideo().getVideoid());
                        map.put("commentTid", "1");
                        map.put("commentContent", comment.getText().toString());
                        XUtils.Get(url, map, new MyCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);
                                try {
                                    JSONObject json = new JSONObject(result);
                                    String code = json.optString("code");
                                    if (code.equals("7100")) {
                                        Toast.makeText(LiveDetailsPage.this, "评论成功", Toast.LENGTH_SHORT).show();
                                        comment.setText("");
                                        mPopWindow2.dismiss();
                                    } else {
                                        Toast.makeText(LiveDetailsPage.this, code + "评论失败", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                super.onError(ex, isOnCallback);
//                                Toast.makeText(LiveDetailsPage.this, ex.getMessage() + "", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onFinished() {
                                super.onFinished();
                                timer.cancel();
                                data(0);
                                //关闭软键盘
                                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                                live_comments_text.setText("评论(" + bean.getComment().size() + ")");
                                like_number.setText(bean.getComment().size());
                            }
                        });
                    }
                } else {
                    startActivity(new Intent(LiveDetailsPage.this,WxLoginPage.class));
                    overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                    Toast.makeText(LiveDetailsPage.this, "用户未登录，请登录后评论", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(LiveDetailsPage.this).inflate(R.layout.activity_article_details_page, null);
        showPopmenu2(rootview);
    }

    private void showPopmenu2(View rootview) {
        mPopWindow2.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        // 显示窗口位置
        mPopWindow2.showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        JCVideoPlayer.releaseAllVideos();
        unregisterReceiver(mRefreshBroadcastReceiver);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }


    private String Days, Hours, Minutes, Seconds;//倒计时显示格式

    public void data(final int refsh) {
        String url = AppUrl.URLS + AppUrl.LiveDetailsURL;
        Map<String, String> map = new HashMap<>();
        map.put("videoId", videoId);
        if (consumerId != null) {
            map.put("consumerId", consumerId);
        }
        XUtils.Get(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                LogU.e("result", result);
                bean = gson.fromJson(result, LiveDetailsBean.class);
                if (refsh != 0) {
                    //
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                    String str = sdf.format(new java.util.Date());
                    time = Long.parseLong(TimeChangeUtil.getTimeStamp(str));//系统当前时间戳
                    long times = Long.parseLong(bean.getVideo().getVideostatime());//活动开始时间戳
                    countdownTime = (times - time) * 1000;
                    if (bean.getVideo().getNeedPay().equals("0")) {
                        if(!bean.getVideo().getVideoprice().equals("0.00")){
                            need_pay.setVisibility(View.VISIBLE);
                        }
                    } else if (bean.getVideo().getNeedPay().equals("1")) {
                        need_pay.setVisibility(View.GONE);
                    }
                    if (bean.getVideo().getPlaystatics().equals("1")) {
                        appointment_button.setText("回放中");
                        huifang.setVisibility(View.GONE);
                        xiahua.setVisibility(View.GONE);
                        if(ApplicationUtils.getInstance().loginBean!=null){
                            if (bean.getVideo().getNeedPay().equals("0") || bean.getVideo().getOrderStatus().equals("1")) {
                                appointment_button.setEnabled(false);
                            } else {
                                appointment_button.setEnabled(true);
                            }
                        }
                        appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                        if (bean.getVideo().getNeedPay().equals("0")) {
                            surface_View.setVisibility(View.VISIBLE);
                            video_image.setVisibility(View.GONE);
                            play.setVisibility(View.GONE);
                        } else if (bean.getVideo().getNeedPay().equals("1")) {
                            if (bean.getVideo().getOrderStatus().equals("0")) {
                                surface_View.setVisibility(View.GONE);
                                video_image.setVisibility(View.VISIBLE);
                                play.setVisibility(View.VISIBLE);
                            } else {
                                surface_View.setVisibility(View.VISIBLE);
                                video_image.setVisibility(View.GONE);
                                play.setVisibility(View.GONE);
                            }
                        }

                    } else if (bean.getVideo().getPlaystatics().equals("0")) {
                        if (countdownTime == 0 || countdownTime < 0) {
                            appointment_button.setText("直播中");
                            if(ApplicationUtils.getInstance().loginBean!=null) {
                                if (bean.getVideo().getNeedPay().equals("0") || bean.getVideo().getOrderStatus().equals("1")) {
                                    appointment_button.setEnabled(false);
                                } else {
                                    appointment_button.setEnabled(true);
                                }
                            }
                            appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                            if (bean.getVideo().getNeedPay().equals("0")) {
                                surface_View.setVisibility(View.VISIBLE);
                                video_image.setVisibility(View.GONE);
                                play.setVisibility(View.GONE);
                            } else if (bean.getVideo().getNeedPay().equals("1")) {
                                if (bean.getVideo().getOrderStatus().equals("0")) {
                                    surface_View.setVisibility(View.GONE);
                                    video_image.setVisibility(View.VISIBLE);
                                    play.setVisibility(View.VISIBLE);
                                } else {
                                    surface_View.setVisibility(View.VISIBLE);
                                    video_image.setVisibility(View.GONE);
                                    play.setVisibility(View.GONE);
                                }
                            }
                        }

                    } else if (bean.getVideo().getPlaystatics().equals("2")) {
                        if (countdownTime > 300) {
                            if (bean.getVideoorder().getStatus().equals("0") || bean.getVideoorder().getStatus().equals("2")) {
                                appointment_button.setText("立即预约");
                                appointment_button.setEnabled(true);
                                appointment_button.setBackgroundResource(R.drawable.shape_order_corner);
                            } else if (bean.getVideoorder().getStatus().equals("1")) {
                                appointment_button.setText("已预约");
                                appointment_button.setEnabled(false);
                                appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                            }
                            surface_View.setVisibility(View.GONE);
                            video_image.setVisibility(View.VISIBLE);
                            play.setVisibility(View.VISIBLE);
                        } else if (0 < countdownTime && countdownTime < 300) {
                            if (bean.getVideoorder().getStatus().equals("0") || bean.getVideoorder().getStatus().equals("2")) {
                                appointment_button.setText("离开始直播不足5分钟");
                                appointment_button.setEnabled(false);
                                appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                            } else if (bean.getVideoorder().getStatus().equals("1")) {
                                appointment_button.setText("已预约");
                                appointment_button.setEnabled(false);
                                appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                            }
                            surface_View.setVisibility(View.GONE);
                            video_image.setVisibility(View.VISIBLE);
                            play.setVisibility(View.VISIBLE);
                        }
                    }

                    String Url = bean.getVideo().getBackimgurl();
                    if (Url != null && !Url.equals("")) {
                        String ImageUrl = Url.substring(1, Url.indexOf("|"));
                        Glide.with(LiveDetailsPage.this)
                                .load(AppUrl.URLS + ImageUrl)
                                .into(video_image);
                    }
                    if (!"1".equals(bean.getSession().getCount())) {
                        bean.getAddvideo().get(bean.getVideo().getArrange()).setClick(1);
                        setVideoList(bean.getAddvideo(), Url);
                        list_line.setVisibility(View.VISIBLE);
                    } else {
                        list_line.setVisibility(View.GONE);
                    }
                    if(ApplicationUtils.getInstance().loginBean==null&&!bean.getVideo().getVideoprice().equals("0.00")){
                        play.setVisibility(View.VISIBLE);
                        need_pay.setVisibility(View.GONE);
                    }

                    live_details_title.setText(bean.getVideo().getVideotitle());
                    live_details_name.setText(bean.getVideo().getVideoauthor());
                    live_details_time.setText(TimeChangeUtil.getStrTimes(bean.getVideo().getVideostatime()));
                    if(!bean.getVideo().getVideoprice().equals("0.00")&&!bean.getVideo().getVideoprice().equals("0")){
                        live_money.setText("¥ " + bean.getVideo().getVideoprice());
                    }else{
                        live_money.setText("免费");
                    }
                    live_number.setText(bean.getVideo().getVideoviewcount());
                    live_up_number.setText(bean.getVideo().getLikecount());
                    live_details_introduce.setText(bean.getVideo().getVideodescribe());
                    stores.setText(bean.getVideo().getHost());
                    tel.setText(bean.getStore().getStoreaddress());
                    msURI = bean.getVideo().getVideopath3();
                    //免费视频不登录也能观看
                    if(bean.getVideo().getVideoprice().equals("0.00")||bean.getVideo().getVideoprice().equals("0")&&!bean.getVideo().getPlaystatics().equals("2")){
                        play.setVisibility(View.GONE);
                        need_pay.setVisibility(View.GONE);
                        surface_View.setVisibility(View.VISIBLE);
                        video_image.setVisibility(View.GONE);
                        if (JCVideoPlayerManager.listener() == null) {
                            boolean setUp = surfaceView.setUp(msURI, JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
                            if (setUp) {
                                String ImageUrl = Url.substring(1, Url.indexOf("|"));
                                Glide.with(LiveDetailsPage.this).load(AppUrl.URLS + ImageUrl)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                                        .centerCrop()
                                        .crossFade()
                                        .into(surfaceView.thumbImageView);
                            }
                        }
                    }
                    if (bean.getVideoorder().getPlay().equals("1") && bean.getVideo().getPlayer().equals("1")) {
                        if (JCVideoPlayerManager.listener() == null) {
                            boolean setUp = surfaceView.setUp(msURI, JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
                            if (setUp) {
                                String ImageUrl = Url.substring(1, Url.indexOf("|"));
                                Glide.with(LiveDetailsPage.this).load(AppUrl.URLS + ImageUrl)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                                        .centerCrop()
                                        .crossFade()
                                        .into(surfaceView.thumbImageView);
                            }
                        }
                    }
                    if (bean.getVideo().getVideoBestStatics().equals("1")) {
                        live_like.setImageResource(R.drawable.praise);
                    } else {
                        live_like.setImageResource(R.drawable.praise_w);
                    }
                    if (timer != null) {
                        timer.cancel();
                    }
                    timer = new CountDownTimer(countdownTime, 1) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            mDisplayDays = (int) ((millisUntilFinished / 1000) / 86400);
                            mDisplayHours = (int) (((millisUntilFinished / 1000) - (mDisplayDays * 86400)) / 3600);
                            mDisplayMinutes = (int) (((millisUntilFinished / 1000) - ((mDisplayDays * 86400) + (mDisplayHours * 3600))) / 60);
                            mDisplaySeconds = (int) ((millisUntilFinished / 1000) % 60);
                            Days = "" + mDisplayDays;
                            Hours = "" + mDisplayHours;
                            Minutes = "" + mDisplayMinutes;
                            Seconds = "" + mDisplaySeconds;
                            if (mDisplayDays < 10) {
                                Days = "0" + mDisplayDays;
                            }
                            if (mDisplayHours < 10) {
                                Hours = "0" + mDisplayHours;
                            }
                            if (mDisplayMinutes < 10) {
                                Minutes = "0" + mDisplayMinutes;
                            }
                            if (mDisplaySeconds < 10) {
                                Seconds = "0" + mDisplaySeconds;
                            }
                            The_countdown.setText(Days + "天 " + Hours + "时 " + Minutes + "分 " + Seconds + "秒");
                        }

                        @Override
                        public void onFinish() {
                            The_countdown.setVisibility(View.GONE);
                        }
                    }.start();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
                Log.e("result", ex.getMessage());
            }

            @Override
            public void onFinished() {
                super.onFinished();
                loadView.setVisibility(View.GONE);
                if (ApplicationUtils.getInstance().loginBean == null&&!bean.getVideo().getVideoprice().equals("0.00")) {
                    surface_View.setVisibility(View.GONE);
                    video_image.setVisibility(View.VISIBLE);
                }
                if (bean.getComment() != null) {
                    live_comments_text.setText("评论(" + bean.getComment().size() + ")");
                    recyclerView();
                } else {
                    live_comments_text.setText("评论(0)");
                }
            }

        });

    }

    private void setVideoList(final List<LiveDetailsBean.AddvideoBean> addvideo, final String url) {
        videoList.setAdapter(new BaseRVAdapter(LiveDetailsPage.this, addvideo) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_more_video;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                TextView text = holder.getTextView(R.id.text);
                if (addvideo.get(position).getClick() == 0) {
                    text.setBackgroundResource(R.drawable.b9_circle_white);
                    text.setTextColor(Color.parseColor("#7FC48D"));
                } else {
                    text.setBackgroundResource(R.drawable.b9_circle_main);
                    text.setTextColor(Color.parseColor("#FFFFFF"));
                }
                text.setText("第" + (position + 1) + "场");
                text.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        JCVideoPlayer.releaseAllVideos();
                        for (int i = 0; i < addvideo.size(); i++) {
                            if (i == position) {
                                addvideo.get(i).setClick(1);
                                showView(addvideo.get(i));
                            } else {
                                addvideo.get(i).setClick(0);
                            }
                        }
                        notifyDataSetChanged();
                    }
                });

            }


        });
    }

    /**
     * 直播多场次
     * @param addvideoBean
     */
    private void showView(LiveDetailsBean.AddvideoBean addvideoBean) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        String str = sdf.format(new java.util.Date());
        time = Long.parseLong(TimeChangeUtil.getTimeStamp(str));//系统当前时间戳
        long times = Long.parseLong(addvideoBean.getVideostatime());//活动开始时间戳
        countdownTime = (times - time) * 1000;
        if ("0".equals(addvideoBean.getNeedPay())) {
            if(!bean.getVideo().getVideoprice().equals("0.00")){
                need_pay.setVisibility(View.VISIBLE);
            }
        } else if ("1".equals(addvideoBean.getNeedPay())) {
            need_pay.setVisibility(View.GONE);
        }
        if ("1".equals(addvideoBean.getPlaystatics())) {
            appointment_button.setText("回放中");
            if(ApplicationUtils.getInstance().loginBean!=null) {
                if ("0".equals(addvideoBean.getNeedPay()) || "1".equals(addvideoBean.getOrderStatus())) {
                    appointment_button.setEnabled(false);
                } else {
                    appointment_button.setEnabled(true);
                }
            }
            appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
            if ("0".equals(addvideoBean.getNeedPay())) {
                surface_View.setVisibility(View.VISIBLE);
                video_image.setVisibility(View.GONE);
                play.setVisibility(View.GONE);
            } else if ("1".equals(addvideoBean.getNeedPay())) {
                if ("0".equals(addvideoBean.getOrderStatus())) {
                    surface_View.setVisibility(View.GONE);
                    video_image.setVisibility(View.VISIBLE);
                    play.setVisibility(View.VISIBLE);
                } else {
                    surface_View.setVisibility(View.VISIBLE);
                    video_image.setVisibility(View.GONE);
                    play.setVisibility(View.GONE);
                }
            }

        } else if ("0".equals(addvideoBean.getPlaystatics())) {
            if (countdownTime == 0 || countdownTime < 0) {
                appointment_button.setText("直播中");
                if(ApplicationUtils.getInstance().loginBean!=null) {
                    if ("0".equals(addvideoBean.getNeedPay()) || "1".equals(addvideoBean.getOrderStatus())) {
                        appointment_button.setEnabled(false);
                    } else {
                        appointment_button.setEnabled(true);
                    }
                }
                appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                if ("0".equals(addvideoBean.getNeedPay())) {
                    surface_View.setVisibility(View.VISIBLE);
                    video_image.setVisibility(View.GONE);
                    play.setVisibility(View.GONE);
                } else if ("1".equals(addvideoBean.getNeedPay())) {
                    if ("0".equals(addvideoBean.getOrderStatus())) {
                        surface_View.setVisibility(View.GONE);
                        video_image.setVisibility(View.VISIBLE);
                        play.setVisibility(View.VISIBLE);
                    } else {
                        surface_View.setVisibility(View.VISIBLE);
                        video_image.setVisibility(View.GONE);
                        play.setVisibility(View.GONE);
                    }
                }
            }

        } else if ("2".equals(addvideoBean.getPlaystatics())) {
            if (countdownTime > 300) {
                if ("0".equals(addvideoBean.getStatus()) || "2".equals(addvideoBean.getStatus())) {
                    appointment_button.setText("立即预约");
                    appointment_button.setEnabled(true);
                    appointment_button.setBackgroundResource(R.drawable.shape_order_corner);
                } else if ("1".equals(addvideoBean.getStatus())) {
                    appointment_button.setText("已预约");
                    appointment_button.setEnabled(false);
                    appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                }
                surface_View.setVisibility(View.GONE);
                video_image.setVisibility(View.VISIBLE);
                play.setVisibility(View.VISIBLE);
            } else if (0 < countdownTime && countdownTime < 300) {
                if ("0".equals(addvideoBean.getStatus()) || "2".equals(addvideoBean.getStatus())) {
                    appointment_button.setText("离开始直播不足5分钟");
                    appointment_button.setEnabled(false);
                    appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                } else if ("1".equals(addvideoBean.getStatus())) {
                    appointment_button.setText("已预约");
                    appointment_button.setEnabled(false);
                    appointment_button.setBackgroundResource(R.drawable.shape_order2_corner);
                }
                surface_View.setVisibility(View.GONE);
                video_image.setVisibility(View.VISIBLE);
                play.setVisibility(View.VISIBLE);
            }
        }
        String Url = addvideoBean.getBackimgurl();
        if (Url != null && !Url.equals("")) {
            String ImageUrl = Url.substring(1, Url.indexOf("|"));
            Glide.with(LiveDetailsPage.this)
                    .load(AppUrl.URLS + ImageUrl)
                    .into(video_image);
        }
        //免费视频不登录也能观看
        if(bean.getVideo().getVideoprice().equals("0.00")||bean.getVideo().getVideoprice().equals("0")&&!bean.getVideo().getPlaystatics().equals("2")){
            play.setVisibility(View.GONE);
            need_pay.setVisibility(View.GONE);
            surface_View.setVisibility(View.VISIBLE);
            video_image.setVisibility(View.GONE);
            if (JCVideoPlayerManager.listener() == null) {
                boolean setUp = surfaceView.setUp(msURI, JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
                if (setUp) {
                    String ImageUrl = Url.substring(1, Url.indexOf("|"));
                    Glide.with(LiveDetailsPage.this).load(AppUrl.URLS + ImageUrl)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .centerCrop()
                            .crossFade()
                            .into(surfaceView.thumbImageView);
                }
            }
        }
        msURI = addvideoBean.getVideopath3();
        if ("1".equals(addvideoBean.getPlay()) && "1".equals(addvideoBean.getPlayer())) {
            boolean setUp = surfaceView.setUp(msURI, JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
            if (setUp) {
                String ImageUrl = Url.substring(1, Url.indexOf("|"));
                Glide.with(LiveDetailsPage.this).load(AppUrl.URLS + ImageUrl)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .centerCrop()
                        .crossFade()
                        .into(surfaceView.thumbImageView);
            }
        }
        if (timer != null) {
            timer.cancel();
        }
        The_countdown.setVisibility(View.VISIBLE);
        timer = new CountDownTimer(countdownTime, 1) {
            @Override
            public void onTick(long millisUntilFinished) {
                mDisplayDays = (int) ((millisUntilFinished / 1000) / 86400);
                mDisplayHours = (int) (((millisUntilFinished / 1000) - (mDisplayDays * 86400)) / 3600);
                mDisplayMinutes = (int) (((millisUntilFinished / 1000) - ((mDisplayDays * 86400) + (mDisplayHours * 3600))) / 60);
                mDisplaySeconds = (int) ((millisUntilFinished / 1000) % 60);
                Days = "" + mDisplayDays;
                Hours = "" + mDisplayHours;
                Minutes = "" + mDisplayMinutes;
                Seconds = "" + mDisplaySeconds;
                if (mDisplayDays < 10) {
                    Days = "0" + mDisplayDays;
                }
                if (mDisplayHours < 10) {
                    Hours = "0" + mDisplayHours;
                }
                if (mDisplayMinutes < 10) {
                    Minutes = "0" + mDisplayMinutes;
                }
                if (mDisplaySeconds < 10) {
                    Seconds = "0" + mDisplaySeconds;
                }
                The_countdown.setText(Days + "天 " + Hours + "时 " + Minutes + "分 " + Seconds + "秒");
            }

            @Override
            public void onFinish() {
                The_countdown.setVisibility(View.GONE);
            }
        }.start();
    }

    private void recyclerView() {//一级评论
        FullyLinearLayoutManager mLinearLayoutManager = new FullyLinearLayoutManager(this);
        mLinearLayoutManager.setScrollEnabled(false);
        live_details_recyclerview.setLayoutManager(mLinearLayoutManager);
        live_details_recyclerview.setNestedScrollingEnabled(false);
        live_details_recyclerview.setHasFixedSize(true);
        liveDetailsAdapter = new LiveDetailCommentAdapter(bean.getComment());
        live_details_recyclerview.setAdapter(liveDetailsAdapter);
    }

    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(LiveDetailsPage.this).inflate(R.layout.appointment_pay_popwindow_page, null);
        mPopWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        payButton = (Button) contentView.findViewById(R.id.pay_button);
        zhifubao = (ImageView) contentView.findViewById(R.id.zhifubao);
        weixin = (ImageView) contentView.findViewById(R.id.weixin);
        money = (TextView) contentView.findViewById(R.id.money);
        zfb = (RelativeLayout) contentView.findViewById(R.id.zfb);
        wx = (RelativeLayout) contentView.findViewById(R.id.wx);
        if (bean != null) {
            money.setText("¥"+bean.getVideo().getVideoprice());
        }
        zfb.setOnClickListener(this);
        wx.setOnClickListener(this);
        payButton.setOnClickListener(this);
        //设置各个控件的点击响应

        //显示PopupWindow
        View rootview = LayoutInflater.from(LiveDetailsPage.this).inflate(R.layout.live_details_page, null);
        showPopmenu(rootview);
    }

    private void showPopmenu(View rootview) {
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        // 显示窗口位置
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
    }

    private void requestPay() {
        String url = AppUrl.URL + AppUrl.payUrl;
        Map<String, String> map = new HashMap<>();
        // 微信
        map.put("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
        map.put("videoId", bean.getVideo().getVideoid());
        map.put("body", bean.getVideo().getVideotitle());
        XUtils.Post(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject obj = new JSONObject(result);
                    // 微信支付回调
                    setWeChat(obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Toast.makeText(LiveDetailsPage.this, ex.getMessage() + "错误", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 微信支付
     */
    private void setWeChat(JSONObject obj) {
        mIwxapi = WXAPIFactory.createWXAPI(this, obj.optString("appid"));
        mIwxapi.registerApp(obj.optString("appid"));// 将应用注册到微信
        if (mIwxapi != null && mIwxapi.isWXAppInstalled()) {// 判断用户有没有安装微信
            PayReq req = new PayReq();
            req.appId = obj.optString("appid");
            req.partnerId = obj.optString("partnerid");
            req.prepayId = obj.optString("prepayid");
            req.nonceStr = obj.optString("noncestr");
            req.timeStamp = obj.optString("timestamp");
            req.packageValue = obj.optString("package");
            req.sign = obj.optString("sign");
            // req.extData = "app data";// 可选
            mIwxapi.sendReq(req);
        } else {
            Toast.makeText(this, "用户未安装微信", Toast.LENGTH_SHORT).show();
            return;
        }
    }

    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(LiveDetailsPage.this, "分享成功", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(LiveDetailsPage.this, "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(LiveDetailsPage.this, "分享取消", Toast.LENGTH_LONG).show();

        }
    };

    /**
     * 分享是否同意的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    }
}
